package com.itheima.topic4;

import org.junit.Assert;
import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Mytest {
    @Test
    public void testPerson() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //创造一个实例
        Class<Person> cls = Person.class;
        Constructor<Person> constructor = cls.getDeclaredConstructor(String.class, int.class);
        Person person = constructor.newInstance("至尊宝", 999);
        //使用反射方式调用setName方法对姓名进行设置
        Method setName = cls.getDeclaredMethod("setName", String.class);
        setName.invoke(person,"紫霞");
        //不使用setAge方法直接使用反射方式对age赋值。
        Field age = cls.getDeclaredField("age");
        age.setAccessible(true);
        age.set(person,888);
        //查看修改结果
        String newName = (String) cls.getDeclaredMethod("getName").invoke(person);
        int newAge = (int) cls.getDeclaredMethod("getAge").invoke(person);
        System.out.println("name:"+newName);    //name:紫霞
        System.out.println("age:"+newAge);      //age:888



    }
}
